import pygame
import sys
import math
import random

from games.ping.Brick import Brick
from games.ping.ball import Ball

pygame.init()
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
# 设置标题
pygame.display.set_caption("Ball Ping")
color = (0, 0, 0)
clock = pygame.time.Clock()

ball = Ball('../../res/image/poke-ball-small.png', 7, 2.0, 2.0, width, height)
ball_group = pygame.sprite.Group()
ball_group.add(ball)

brick_images = ['../../res/image/rect_blue.jpg',
                '../../res/image/rect_green.jpg',
                '../../res/image/rect_purple.jpg',
                '../../res/image/rect_red.jpg',
                '../../res/image/rect_yellow.jpg']
brick_group = pygame.sprite.Group()
for i in range(160):
    brick = Brick(brick_images[random.randint(0, 4)], 40 * (i % 16), 15 * (int(i / 16)))
    brick_group.add(brick)

while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    screen.fill(color)
    for b in ball_group.sprites():
        collides = pygame.sprite.spritecollide(b, brick_group, True)
        if collides:
            for c in collides:
                dist_x = 27.5 - math.fabs(b.rect.x - c.rect.x - 12.5)
                dist_y = 14.5 - math.fabs(b.rect.y - c.rect.y)
                if dist_x > 0 and dist_y > 0:
                    dist = dist_x - dist_y
                    if dist > 2:
                        b.attack(Ball.ATTACK_TB)
                    elif dist < -2:
                        b.attack(Ball.ATTACK_LR)
                    else:
                        b.attack(Ball.ATTACK_TB)
                        b.attack(Ball.ATTACK_LR)
                print('sprite collide {}, {}'.format(b.rect.x, b.rect.y))

    ball_group.update(pygame.time.get_ticks())
    ball_group.draw(screen)
    brick_group.draw(screen)
    pygame.display.update()

pygame.quit()
